package com.woniu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.client.AccountClient;
import com.woniu.client.VenueClient;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.Result;
import com.woniu.commons.model.StateData;
import com.woniu.dao.mapper.YClassTypeMapper;
import com.woniu.dao.mapper.YLeagueClassMapper;
import com.woniu.dao.mapper.YLeagueWorkforceMapper;
import com.woniu.model.YCoach;
import com.woniu.model.YVenueClassroom;
import com.woniu.model.dto.LeagueClassDto;
import com.woniu.model.dto.MyCourseDto;
import com.woniu.model.model.YClassType;
import com.woniu.model.model.YLeagueClass;
import com.woniu.model.model.YLeagueWorkforce;
import com.woniu.model.param.*;
import com.woniu.service.YLeagueClassService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class YLeagueClassServiceImpl extends ServiceImpl<YLeagueClassMapper, YLeagueClass> implements YLeagueClassService {

    @Resource
    private YLeagueClassMapper leagueClassMapper;
    @Resource
    private YClassTypeMapper classTypeMapper;
    @Resource
    private AccountClient accountClient;
    @Resource
    private VenueClient venueClient;
    @Resource
    private YLeagueWorkforceMapper leagueWorkforceMapper;

    /**
     * 新增团课
     *
     * @param param：leagueClassName：团课名；coachId：教练名；peopleNum：课程容纳人数；venueId：场馆id；price：价格；minute：分钟数(课程时长)；classTypeId：课程类型id；leagueClassState：0.已取消1.可预约2.预约满3.已完课；leagueClassDetail：课程描述；classroomId：教室id；classNum：课程数量（节）
     * @return
     * @throws YogaException
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public void addLeagueClass(LeagueClassAddParam param) throws YogaException {
//        System.out.println(param);
        Result<YCoach> coach = accountClient.byId(param.getCoachId());
        if (coach == null) {
            throw new YogaException(500, "教练不存在，请重新输入");
        }
        Result<?> venue = venueClient.loadVenueBaseById(param.getVenueId());
        if (venue == null) {
            throw new YogaException(500, "场馆不存在，请重新输入");
        }
        if (param.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new YogaException(500, "输入价格有误，请重新输入");
        }
        System.out.println(param.getClassroomId());

        Result<YVenueClassroom> yVenueClassroomResult = venueClient.loadClassroomById(param.getClassroomId());
        YVenueClassroom classroom = yVenueClassroomResult.getData();

        if (param.getPeopleNum() > classroom.getPeopleNum()) {
            throw new YogaException(500, "人数大于教室人数，请重新输入");
        }
        YLeagueClass yLeagueClass = new YLeagueClass();
        yLeagueClass.setLeagueClassName(param.getLeagueClassName());
        yLeagueClass.setCoachId(param.getCoachId());
        yLeagueClass.setPeopleNum(param.getPeopleNum());
        yLeagueClass.setVenueId(param.getVenueId());
        yLeagueClass.setPrice(param.getPrice());
        yLeagueClass.setMinute(param.getMinute());
        yLeagueClass.setClassTypeId(param.getClassTypeId());
        yLeagueClass.setLeagueClassState(4);
        yLeagueClass.setLeagueClassDetail(param.getLeagueClassDetail());
        yLeagueClass.setClassroomId(param.getClassroomId());
        yLeagueClass.setClassNum(param.getClassNum());

        leagueClassMapper.insert(yLeagueClass);
    }


    /**
     * 修改团课状态为已完课：
     *
     * @param param：leagueClassId：团课id；leagueClassState：状态
     * @return
     * @throws YogaException
     */
    @Override
    public void updateLeagueClassState(LeagueClassUpdateStateParam param) throws YogaException {
        YLeagueClass yLeagueClass = leagueClassMapper.selectById(param.getLeagueClassId());
        if (yLeagueClass == null) {
            throw new YogaException(500, "团课不存在，请重新输入");
        }
        if (Objects.equals(yLeagueClass.getLeagueClassState(), param.getLeagueClassState())) {
            throw new YogaException(500, "状态已为完成，请勿重新提交");
        }

        yLeagueClass.setLeagueClassState(param.getLeagueClassState());
        leagueClassMapper.updateById(yLeagueClass);
    }

    /**
     * 通过团课Id查一个团课
     *
     * @param id：团课id
     * @return
     */
    @Override
    public YLeagueClass ByIdLeagueClass(Integer id) throws YogaException {
        // 通过ID查询YLeagueClass对象
        YLeagueClass yLeagueClass = leagueClassMapper.selectOne(new QueryWrapper<YLeagueClass>().eq("league_class_id",id));

        // 检查是否查询到对象以及其状态是否为0
        if (yLeagueClass == null || yLeagueClass.getLeagueClassState() == 0) {
            throw new YogaException(500, "未找到符合条件的团课");
        }

        return yLeagueClass;
    }

    /**
     * 删除团课
     *
     * @param leagueClassId：团课id
     * @return
     * @throws YogaException
     */
    @Override
    public void deleteLeagueClassState(Integer leagueClassId) throws YogaException {
        YLeagueClass yLeagueClass = leagueClassMapper.selectById(leagueClassId);
        if (yLeagueClass == null) {
            throw new YogaException(500, "团课不存在，请重新输入");
        }
        if (yLeagueClass.getLeagueClassState() == StateData.LEAGUE_CLASS_STATE_DISABLED) {
            throw new YogaException(500, "状态已为删除，请勿重新提交");
        }

        yLeagueClass.setLeagueClassState(StateData.LEAGUE_CLASS_STATE_DISABLED);
        leagueClassMapper.updateById(yLeagueClass);
    }

    /**
     * 通过教练Id查该教练的团课
     *
     * @param coachId：教练id
     * @return
     */
    @Override
    public List CoachByIdLeagueClass(Integer coachId) throws YogaException {
        QueryWrapper<YLeagueClass> wrapper = new QueryWrapper<>();
        wrapper.eq("coach_id", coachId);
        List<YLeagueClass> yLeagueClasses = leagueClassMapper.selectList(wrapper);
        return yLeagueClasses;
    }



    /**
     * 通过场馆Id查该场馆的团课
     *
     * @param venueId：场馆id
     * @return
     */
    @Override
    public List VenueByIdLeagueClass(Integer venueId) throws YogaException {
        QueryWrapper<YLeagueClass> wrapper = new QueryWrapper<>();
        wrapper.eq("venue_id", venueId);
        List<YLeagueClass> yLeagueClasses = leagueClassMapper.selectList(wrapper);
        return yLeagueClasses;
    }

    /**
     * 分页查询所有团课
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public Page<LeagueClassDto> pageAllLeagueClass(PageAllLeagueClassParam param) throws YogaException {
        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        //拼接条件
        QueryWrapper<YLeagueClass> wrapper = new QueryWrapper<YLeagueClass>();
        wrapper.ne("league_class_state",0);
        wrapper.eq("coach_id",param.getCoachId());
        Page<YLeagueClass> leagueClassPage = baseMapper.selectPage(new Page<YLeagueClass>(param.getPageNum(), param.getPageSize()), wrapper);

        Page<LeagueClassDto> page = new Page<>();
        page.setCurrent(leagueClassPage.getCurrent());
        page.setOptimizeCountSql(leagueClassPage.optimizeCountSql());
        page.setPages(leagueClassPage.getPages());
        page.setSearchCount(leagueClassPage.searchCount());
        page.setSize(leagueClassPage.getSize());
        page.setTotal(leagueClassPage.getTotal());

        ArrayList<LeagueClassDto> dto = new ArrayList<>();

        for (YLeagueClass leagueClass:leagueClassPage.getRecords()){
            LeagueClassDto pageDto = BeanUtil.toBean(leagueClass, LeagueClassDto.class);

            //通过教练ID查出教练名字赋值给dto
            String coachName = accountClient.byId(leagueClass.getCoachId()).getData().getCoachName();
            if (coachName == null){
                throw new YogaException(500,"请先招募教练");
            }
            pageDto.setCoachName(coachName);

            //通过场馆ID查出场馆名字
            String venueName = accountClient.venueById(leagueClass.getVenueId()).getData().getVenueName();
            if (venueName == null){
                throw new YogaException(500,"场馆不存在");
            }
            pageDto.setVenueName(venueName);

            //通过课程类型id查出课程类型名字
            YClassType yClassType = classTypeMapper.selectById(leagueClass.getClassTypeId());
            if (yClassType==null){
                throw new YogaException(500,"类型不存在");
            }
            pageDto.setClassTypeName(yClassType.getClassTypeName());





            dto.add(pageDto);
        }
        page.setRecords(dto);
        return page;
    }

    @Override
    public Page<MyCourseDto> CoachLeagueClassMessage(CoachMessageParam param) throws YogaException {
        if (param.getPageNum()==0){
            param.setPageNum(1);
        }
        if (param.getPageSize()==0){
            param.setPageSize(5);
        }
        QueryWrapper<YLeagueClass> wrapper = new QueryWrapper<>();
        wrapper.eq("coach_id",param.getCoachId());
        Page<YLeagueClass> Y=leagueClassMapper.selectPage(new Page<>(param.getPageNum(),param.getPageSize()),wrapper);
        Page<MyCourseDto> page = new Page<>();
        page.setCurrent(Y.getCurrent());
        page.setOptimizeJoinOfCountSql(Y.optimizeJoinOfCountSql());
        page.setPages(Y.getPages());
        page.setSearchCount(Y.searchCount());
        page.setSize(Y.getSize());
        page.setTotal(Y.getTotal());


        ArrayList<MyCourseDto> courseDtos = new ArrayList<>();
        for (YLeagueClass yLeagueClass: Y.getRecords()){
            MyCourseDto dto = BeanUtil.toBean(yLeagueClass, MyCourseDto.class);


            String venueName = venueClient.venueIdByVenueBase(yLeagueClass.getVenueId()).getData().getVenueName();
            System.out.println("其他接口查出来的"+venueName);
            dto.setVenueName(venueName);
            //根课程类型ID查询课程名
            String typeName = classTypeMapper.selectById(yLeagueClass.getClassTypeId()).getClassTypeName();
            dto.setClassTypeName(typeName);
            //根课教室ID查询教室号
            Integer classroomId = venueClient.loadClassroomById(yLeagueClass.getClassroomId()).getData().getClassroomId();
            dto.setClassroomId(classroomId);
            //教室类型
            String classroomType = venueClient.loadClassroomById(yLeagueClass.getClassroomId()).getData().getClassroomType();
            dto.setClassroomType(classroomType);

            courseDtos.add(dto);

        }
        page.setRecords(courseDtos);
        return  page;
    }



    /**
     * 场馆端分页查询自己场馆的所有团课
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public Page<LeagueClassDto> VenuePageMyLeagueClass(VenuePageLeagueClassParam param) {

        if (param.getPageNum() == null) {
            param.setPageNum(1);
        }
        if (param.getPageSize() == null) {
            param.setPageSize(5);
        }

        //拼接条件
        QueryWrapper<YLeagueClass> wrapper = new QueryWrapper<YLeagueClass>();
        wrapper.ne("league_class_state",0);
        wrapper.eq("venue_id",param.getVenueId());
        Page<YLeagueClass> leagueClassPage = baseMapper.selectPage(new Page<YLeagueClass>(param.getPageNum(), param.getPageSize()), wrapper);

        Page<LeagueClassDto> page = new Page<>();
        page.setCurrent(leagueClassPage.getCurrent());
        page.setOptimizeCountSql(leagueClassPage.optimizeCountSql());
        page.setPages(leagueClassPage.getPages());
        page.setSearchCount(leagueClassPage.searchCount());
        page.setSize(leagueClassPage.getSize());
        page.setTotal(leagueClassPage.getTotal());

        ArrayList<LeagueClassDto> dto = new ArrayList<>();

        for (YLeagueClass leagueClass:leagueClassPage.getRecords()){
            LeagueClassDto pageDto = BeanUtil.toBean(leagueClass, LeagueClassDto.class);

            //通过教练ID查出教练名字赋值给dto
            String coachName = accountClient.byId(leagueClass.getCoachId()).getData().getCoachName();
            if (coachName == null){
                throw new YogaException(500,"请先招募教练");
            }
            pageDto.setCoachName(coachName);

            //通过场馆ID查出场馆名字
            String venueName = accountClient.venueById(leagueClass.getVenueId()).getData().getVenueName();
            if (venueName == null){
                throw new YogaException(500,"场馆不存在");
            }
            pageDto.setVenueName(venueName);

            //通过课程类型id查出课程类型名字
            YClassType yClassType = classTypeMapper.selectById(leagueClass.getClassTypeId());
            if (yClassType==null){
                throw new YogaException(500,"类型不存在");
            }
            pageDto.setClassTypeName(yClassType.getClassTypeName());

            //通过教室id查出教室名
            Result<YVenueClassroom> classroom = venueClient.loadClassroomById(leagueClass.getClassroomId());
            if (classroom==null){
                throw new YogaException(500,"教室不存在");
            }
            pageDto.setIdClassroom(classroom.getData().getClassroomId());

            dto.add(pageDto);
        }
        page.setRecords(dto);
        return page;
    }

    /**
     * 团课上架
     * @param leagueClassId
     * @param venueId
     */
    @Override
    public void VenuePutawayLeagueClass(Integer leagueClassId, Integer venueId) {

        List<YLeagueWorkforce> list = leagueWorkforceMapper.selectList(new QueryWrapper<YLeagueWorkforce>().eq("league_class_id", leagueClassId).ne("league_class_workforce_state", StateData.LEAGUE_CLASS_STATE_DISABLED));
        YLeagueClass leagueClass = baseMapper.selectOne(new QueryWrapper<YLeagueClass>().eq("league_class_id", leagueClassId));
        if (!leagueClass.getVenueId().equals(venueId)){
            throw new YogaException(3503,"场馆无权限");
        }
        if (leagueClass.getClassNum() > list.size()){
            throw new YogaException(3502,"排课数量不足，无法上架");
        }
        leagueClass.setLeagueClassState(StateData.LEAGUE_CLASS_STATE_START);
        baseMapper.updateById(leagueClass);
    }

    @Override
    public List<YLeagueClass> loadAllLeagueClass() {

        return baseMapper.selectList(new QueryWrapper<YLeagueClass>());
    }

    @Override
    public List<YLeagueClass> loadLeagueClassByName(String leagueClassName) {
        List<YLeagueClass> list = baseMapper.selectList(new QueryWrapper<YLeagueClass>().like("league_class_name", leagueClassName));
        return list;


    }


    /**
     * 查询团课集合,带团课名搜索条件查询
     * @return
     */
    @Override
    public List loadListByLeagueClass(String LeagueClassName) {
        QueryWrapper<YLeagueClass> wrapper = new QueryWrapper<>();
        if (LeagueClassName!=null){
            wrapper.like("league_class_name",LeagueClassName);
        }
        wrapper.ne("league_class_state", 0);
        List<YLeagueClass> list = leagueClassMapper.selectList(wrapper);
        return list;
    }


    /**
     * 查询团课集合
     *
     * @return
     */
    @Override
    public List loadListLeagueClass() throws YogaException {
        QueryWrapper<YLeagueClass> wrapper = new QueryWrapper<>();
        wrapper.ne("league_class_state", 0);
        List<YLeagueClass> list = leagueClassMapper.selectList(wrapper);
        return list;
    }
}
